package com.payment.system.domain.wxpay;

import java.security.MessageDigest;
import java.util.SortedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WxPayUtil {

	static Logger logger = LoggerFactory.getLogger(WxPayUtil.class);

	/**
	 * 签名
	 * 
	 * @param map
	 * @return
	 */
	public static String sign(SortedMap<String, Object> map) {
		// 根据参数创建集合M，转化成字符串StringA
		String stringA = createStringA(map);
		logger.debug("StringA: " + stringA);
		// 拼接API密钥
		String stringSignTemp = stringA + "&key=" + WxAppPayConfig.instance().key;
		logger.debug("stringSignTemp: " + stringSignTemp);
		// 签名
		String s = MD5Encode(stringSignTemp);
		logger.debug("sign: " + s);
		return s;
	}

	/**
	 * 根据参数创建集合M，转化成字符串StringA
	 * 
	 * @param map
	 * @return
	 */
	private static String createStringA(SortedMap<String, Object> map) {
		StringBuffer sb = new StringBuffer();
		for (Object key : map.keySet()) {
			sb.append(key.toString() + "=" + map.get(key) + "&");
		}
		return sb.substring(0, sb.length() - 1);
	}

	/**
	 * 对参数进行签名
	 * @param stringSignTemp
	 * @return
	 */
	private static String MD5Encode(String stringSignTemp) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		String encodingStr = null;
		try {
			byte[] strTemp = stringSignTemp.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char[]  str= new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			encodingStr = new String(str);
		} catch (Exception e) {
			logger.info("签名失败");
			e.printStackTrace();
		}
		return encodingStr==null?null:encodingStr.toUpperCase();
	}
	
	public static void main(String[] args) {
		//api密钥（E5CDE84017DA36C1771C4FE28B28C9A8）
		System.out.println(MD5Encode(""));
	}
}
